package com.sxt.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.sxt.entity.Basket;
import com.sxt.entity.User;
import com.sxt.model.MoneyResult;
import com.sxt.model.ShopCartItem;
import com.sxt.service.BasketService;
import com.sxt.vo.basket.CartResultVo;
import com.sxt.vo.basket.ShopCartItemDiscount;

/**
 * 实现购物车的相关接口
 * @author WHSXT-LTD
 *
 */
@RestController
public class BasketController {

	@Autowired 
	private BasketService basketService ;
	/**
	 * 怎么添加到购物车里面
	 * @param basket
	 * @return
	 */
	//1 添加购物车
	@PostMapping("/p/shopCart/changeItem")
	public ResponseEntity<Void> addCart(@RequestBody Basket basket){
		User user = (User)SecurityUtils.getSubject().getPrincipal();
		basket.setUserId(user.getUserId()) ;
		basketService.addCart(basket);
		return ResponseEntity.ok().build();
	}
	
	// 2 获取总条数
    @GetMapping("/p/shopCart/prodCount")
	public ResponseEntity<Integer> getTotal(){
    	User user = (User)SecurityUtils.getSubject().getPrincipal();
    	Integer totalCount = basketService.getTotalCount(user.getUserId());
    	return ResponseEntity.ok(totalCount) ;
	}
    
    /**
     * 购物车数据的回显
     */
    @PostMapping("/p/shopCart/info")
    public ResponseEntity<List<CartResultVo>> cartInfo(){
    	User user = (User)SecurityUtils.getSubject().getPrincipal();
    	List<ShopCartItem> shopCartItems = basketService.getCartInfo(user.getUserId());
    	return ResponseEntity.ok(builderResult(shopCartItems)); // 这一步不重要
    }

    
    @PostMapping("/p/shopCart/totalPay")
    public ResponseEntity<MoneyResult> getTotalMoney(@RequestBody List<Long> basketIds){
    	MoneyResult moneyResult = basketService.getTotalMoney(basketIds);
    	return ResponseEntity.ok(moneyResult);
    	
    }
    /**
     * 这一步不是很重要，目的是给前端准备数据
     * @param shopCartItems
     * @return
     */
	private List<CartResultVo> builderResult(List<ShopCartItem> shopCartItems) {
		List<CartResultVo> cartResultVos = new ArrayList<CartResultVo>(1);
		CartResultVo cartResultVo = new CartResultVo();
		List<ShopCartItemDiscount> shopCartItemDiscounts = new ArrayList<ShopCartItemDiscount>();
		ShopCartItemDiscount shopCartItemDiscount = new ShopCartItemDiscount();
		shopCartItemDiscount.setShopCartItems(shopCartItems); // 将购物车的数据放在里面
		shopCartItemDiscounts.add(shopCartItemDiscount );
		
		cartResultVo.setShopCartItemDiscounts(shopCartItemDiscounts );
		cartResultVos.add(cartResultVo) ;
		return cartResultVos;
	}
}
